package com.rocksdata.mc.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.utils.DateUtil;
import com.ctz.commonframe.utils.Logger;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.business.CampusAppManager;
import com.rocksdata.mc.entity.AppWidgetInfo;
import com.rocksdata.mc.entity.DayCourseInfo;
import com.rocksdata.mc.entity.WeekTimetableInfo;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.BusinessInterface;
import com.rocksdata.mc.entity.CourseInfo;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by 陈堂正 on 2017/5/12.
 */

public class TimetableWidgetView extends BaseWidgetView {
    private LinearLayout layoutCourse1;
    private TextView tvDate1;
    private TextView tvWeekday1;
    private TextView tvIndex1;
    private TextView tvCourse1;
    private LinearLayout layoutCourse2;
    private TextView tvDate2;
    private TextView tvWeekday2;
    private TextView tvIndex2;
    private TextView tvCourse2;
    private View vDivide;
    private TextView tvTip;

//    private WeekTimetableInfo weekTimetableInfo;
    private List<DayCourseInfo> dayCourseInfoList = new ArrayList<>();
//    private CourseInfo nextCourse;
    private long weekLastDayMillis;

    public TimetableWidgetView(Context context) {
        super(context);
    }

    public TimetableWidgetView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setupHeadView() {
        ivIcon.setImageResource(R.mipmap.ic_widget_timetable);
        tvName.setText("上课");
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onEnterAppListener != null){
                    onEnterAppListener.onEnterApp(AppWidgetInfo.TYPE_TIMETABLE);
                }
            }
        };
        layoutHead.setOnClickListener(listener);
    }

    @Override
    public View getContentView() {
        @SuppressLint("InflateParams")
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.widget_timetable, null);
        layoutCourse1 = contentView.findViewById(R.id.layout_course1);
        tvDate1 = contentView.findViewById(R.id.tv_course_date1);
        tvWeekday1 = contentView.findViewById(R.id.tv_course_weekday1);
        tvIndex1 = contentView.findViewById(R.id.tv_course_index1);
        tvCourse1 = contentView.findViewById(R.id.tv_course1);
        layoutCourse2 = contentView.findViewById(R.id.layout_course2);
        tvDate2 = contentView.findViewById(R.id.tv_course_date2);
        tvWeekday2 = contentView.findViewById(R.id.tv_course_weekday2);
        tvIndex2 = contentView.findViewById(R.id.tv_course_index2);
        tvCourse2 = contentView.findViewById(R.id.tv_course2);
        vDivide = contentView.findViewById(R.id.view_divide);
        tvTip = contentView.findViewById(R.id.tv_course_tip);

        layoutCourse1.setVisibility(View.GONE);
        layoutCourse2.setVisibility(View.GONE);
        vDivide.setVisibility(View.GONE);
        tvTip.setVisibility(View.GONE);

        return contentView;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void bindData() {
        if (dayCourseInfoList.size() > 0 ){
            DayCourseInfo lastDayCourseInfo = dayCourseInfoList.get(dayCourseInfoList.size() - 1);
            String weekLastDayDate = lastDayCourseInfo.getDay_date();
            weekLastDayMillis = DateUtil.string2Millis(weekLastDayDate, DateUtil.DATE_FORMAT_YYYY_MM_DD);
            if (weekLastDayMillis - System.currentTimeMillis() > 7 * DateUtil.MILLIS_PER_DAY){
                showRecentTwoCourses();
            }else{
                getWeekCourseInfo();
            }
        }else{
            getWeekCourseInfo();
        }
    }

    @Override
    public void release() {

    }

    private void showNoCourse(){
        tvTip.setVisibility(View.VISIBLE);
        layoutCourse1.setVisibility(View.GONE);
        layoutCourse2.setVisibility(View.GONE);
        vDivide.setVisibility(View.GONE);
        int day = (int) Math.ceil((weekLastDayMillis - System.currentTimeMillis()) / (double)DateUtil.MILLIS_PER_DAY);
        tvTip.setText("您最近" + day + "天内无课");
    }

    private void showRecentTwoCourses() {
        List<CourseInfo> courseInfoList = new ArrayList<>();
        for (DayCourseInfo dayCourseInfo: dayCourseInfoList) {
            courseInfoList.addAll(dayCourseInfo.getCourses());
        }
        if (courseInfoList.size() == 0) {
            showNoCourse();
        } else {
            Collections.sort(courseInfoList, new Comparator<CourseInfo>() {
                @Override
                public int compare(CourseInfo o1, CourseInfo o2) {
                    long dt1 = DateUtil.string2Millis(o1.getTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD + " " + DateUtil.TIME_FORMAT_HH_MM_SS);
                    long dt2 = DateUtil.string2Millis(o2.getTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD + " " + DateUtil.TIME_FORMAT_HH_MM_SS);
                    if (dt1 > dt2) {
                        return 1;
                    } else if (dt1 < dt2) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            List<CourseInfo> recentTwoCourses = new ArrayList<>();
            for (CourseInfo info : courseInfoList) {
                long millis = DateUtil.string2Millis(info.getTime(), DateUtil.DATE_FORMAT_YYYY_MM_DD + " " + DateUtil.TIME_FORMAT_HH_MM_SS);
                if (millis + DateUtil.MILLIS_PER_MINUTE * 30 > System.currentTimeMillis()) {
                    recentTwoCourses.add(info);
                }
                if (recentTwoCourses.size() == 2) {
                    break;
                }
            }
            if (recentTwoCourses.size() == 0) {
                showNoCourse();
            } else {
                tvTip.setVisibility(View.GONE);
                layoutCourse2.setVisibility(View.GONE);
                vDivide.setVisibility(View.GONE);
                layoutCourse1.setVisibility(View.VISIBLE);
                final CourseInfo course1 = recentTwoCourses.get(0);
                tvDate1.setText(getDay(course1.getTime()));
                tvWeekday1.setText(getWeekDay(course1.getTime()));
                tvIndex1.setText(course1.getLesson() + "");
                tvCourse1.setText(course1.getClassName() + "\t《" + course1.getCourseName() + "》");
                layoutCourse1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            Intent appIntent = new Intent();
                            String className = "com.ctz.commonframe.ui.WebViewActivity";
                            String router = "#/timetable/day2/" + course1.getTime().substring(0, 10);
                            String url = CampusAppManager.getWebCampusAppUrl(router);
                            appIntent.putExtra(WebViewActivity.EXTRA_KEY_URL, url);
                            appIntent.setClassName(mContext, className);
                            mContext.startActivity(appIntent);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                });
                if(recentTwoCourses.size() == 2){
                    layoutCourse2.setVisibility(View.VISIBLE);
                    vDivide.setVisibility(View.VISIBLE);
                    final CourseInfo course2 = recentTwoCourses.get(1);
                    tvDate2.setText(getDay(course2.getTime()));
                    tvWeekday2.setText(getWeekDay(course2.getTime()));
                    tvIndex2.setText(course2.getLesson() + "");
                    tvCourse2.setText(course2.getClassName() + "\t《" + course2.getCourseName() + "》");
                    layoutCourse2.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                Intent appIntent = new Intent();
                                String className = "com.ctz.commonframe.ui.WebViewActivity";
                                String router = "#/timetable/day2/" + course2.getTime().substring(0, 10);
                                String url = CampusAppManager.getWebCampusAppUrl(router);
                                Logger.e("dayTimetable url:" + url);
                                appIntent.putExtra(WebViewActivity.EXTRA_KEY_URL, url);
                                appIntent.setClassName(mContext, className);
                                mContext.startActivity(appIntent);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
    }

    private void getWeekCourseInfo() {
        BusinessInterface.ITimetableManager manager = BusinessManager.getTimetableManager();
        if (manager != null) {
            manager.getWeekTimetable(new BusinessInterface.OnBusinessResultListener() {
                @Override
                public void onBusinessResult(boolean isSuccess, Object object, String message) {
                    if(isSuccess) {
                        WeekTimetableInfo info = (WeekTimetableInfo) object;
                        dayCourseInfoList = info.getSchedules();
                        DayCourseInfo lastDayCourseInfo = dayCourseInfoList.get(dayCourseInfoList.size() - 1);
                        String weekLastDayDate = lastDayCourseInfo.getDay_date();
                        weekLastDayMillis = DateUtil.string2Millis(weekLastDayDate, DateUtil.DATE_FORMAT_YYYY_MM_DD);
                        showRecentTwoCourses();
                    }
                }
            });
        }
    }

    private String getDay(String time){
        if (time == null || time.length() < 11)
            return "";
        return time.substring(8, 10);
    }

    private String getWeekDay(String time){
        if (TextUtils.isEmpty(time))
            return "";
        String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
        Calendar cal = Calendar.getInstance();
        long millis = DateUtil.string2Millis(time, DateUtil.DATE_FORMAT_YYYY_MM_DD + " " + DateUtil.TIME_FORMAT_HH_MM_SS);
        cal.setTimeInMillis(millis);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
}
